<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/8/25
 * Time: 14:18
 */

namespace app\common;


use think\Db;

class wx_common
{
    private static $instance;
    public $appid;
    public $secret;
    public $access_token;
    private function __construct()
    {
        $config = config('wechat');
        $this->appid = $config['app_id'];
        $this->secret = $config['secret'];
        $this->mini_appid = $config['mini_app_id'];
        $this->mini_secret = $config['mini_secret'];
//        $this->access_token = $this->get_wx_access_token();
    }

    public static function getInstance()
    {
        if(!isset(self::$instance)){
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 微信小程序登陆code换取openid
     */
    public function wx_miniprogram_login($code)
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$this->mini_appid."&secret=".$this->mini_secret."&js_code=".$code."&grant_type=authorization_code";
        $res = $this->creat_curl($url);
        $data = json_decode($res,true);
        return $data;
    }

    /**
     * 获取微信的access_token,并保存到cookie中
     */
    public function get_wx_access_token()
    {
        $access_token = \cache('wx_access_token');
        if($access_token!=null){
            $this->access_token = $access_token;

            return $this;
        }
        $url_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret;
        $res = $this->creat_curl($url_token);
        $json_obj = json_decode($res,true);
//        dump($json_obj);
        if(isset($json_obj["errcode"])){
            trace('wx_access_token:'.json_encode($res),'error');

            return false;
        }else{
            $expires_in = $json_obj['expires_in'];
            $access_token = $json_obj["access_token"];
            \cache('wx_access_token',$access_token,$expires_in);
            $this->access_token = $json_obj["access_token"];
            return $this;
        }
    }

    /**
     * @return mixed
     * 微信微信jsapi_ticket
     */
    public function get_jsapi_ticket()
    {
        $jsapi_ticket = cache('jsapi_ticket');
        if($jsapi_ticket != null)
        {
            return $jsapi_ticket;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$this->access_token."&type=jsapi";
        $res = self::creat_curl($url);
        $res = json_decode($res, true);
        if($res['errmsg'] == 'ok'){

            $expires_in = $res['expires_in'];
            $jsapi_ticket = $res["ticket"];
            \cache('jsapi_ticket',$jsapi_ticket,$expires_in);
            return $jsapi_ticket;
        }else{

            trace('wx_jsapi_ticket:'.json_encode($res),'error');
//            return $res['errcode'];
        }
    }

    /**
     * @return mixed
     * 获取微信卡券api_ticket
     */
    public function get_api_ticket()
    {
        $api_ticket = cache('api_ticket');
        if($api_ticket != null)
        {
            return $api_ticket;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$this->access_token."&type=wx_card";
        $res = self::creat_curl($url);
        $res = json_decode($res, true);
        if($res['errmsg'] == 'ok'){
            $expires_in = $res['expires_in'];
            $api_ticket = $res["ticket"];
            \cache('api_ticket',$api_ticket,$expires_in);
            return $api_ticket;
        }else{
            trace('wx_api_ticket:'.json_encode($res),'error');

//            return $res['errcode'];
        }
    }

    /**
     * 生成带参数的公众号二维码url
     */
    public static function get_ticket($id,$type=1)
    {
        //生成二维码ticket
//        $access_token = self::get_wx_access_token();
        //临时二维码
        $type1 = 'QR_STR_SCENE';
        //永久二维码
        $type2 = 'QR_LIMIT_STR_SCENE';

        $action_name = $type==1?$type1:$type2;

        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
        //scene_str字符串型
        //scene_id 整形
        $json = '{"expire_seconds": 2591999,"action_name": "'.$action_name.'", "action_info": {"scene": {"scene_str": '.$id.'}}}';

        $res = self::creat_curl($url,$json);
        $res = json_decode($res, true);

        if(isset($res["errcode"])){
            echo "错误码：".$res["errcode"]."<br/>报错信息：".$res["errmsg"];
            exit;
        }
        //将ticket换取二维码
        $ticket = urlencode($res["ticket"]);
        //需要进行转码才能用
        $url_ma = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket;
        return $url_ma;
    }

    /**
     * @param $url 微信api接口
     * @param null $data post数据格式（json）
     * @return mixed 返回json数据
     *  链接微信api接口
     */
    public function creat_curl($url,$data=null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //post传输
        if($data) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    //获取指定长度的随机字符串
    public static function getRandChar($length)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;
        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
        return $str;
    }

    /**
     * @param $id
     * @return mixed
     * 派单向平台推送微信模版消息
     */
    public function refused_send_wx_msg($order_id,$shop_id)
    {
        $order = Db::name('order')->where('id',$order_id)->find();
        $config = Db::name('config')->find();
        $shop = Db::name('shop')->where('id',$shop_id)->find();
        $openid = $config['wx_openid'];
        if($openid){
            $config = config('sys');
            $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$this->access_token;

            $data['touser'] = $openid;
            $data['template_id'] = $config['shop_wxmsg_model'];
            $data['data']['first']['value'] = $shop['shop_name'].'拒绝了一个上门维修订单';
            $data['data']['keyword1']['value'] = $order['model'];
            $data['data']['keyword2']['value'] = $order['amount'];
            $data['data']['keyword3']['value'] = $order['linkman'];
            $data['data']['keyword4']['value'] = $order['linktel'];
            $data['data']['keyword5']['value'] = $order['order_no'];
            $data['data']['remark']['value'] = '地址:'.$order['address'].',维修内容：'.$order['malfunction'].',预约维修时间:'.date('Y-m-d H:i',$order['service_time']);


            $data = json_encode($data);

            $res = $this->creat_curl($url,$data);
            $res = json_decode($res,true);
            return $res;
        }else{
            return 0;
        }
    }

    /**
     *
     */
    public function get_wx_card($offset,$count)
    {
        $url = 'https://api.weixin.qq.com/card/batchget?access_token='.$this->access_token;
        $data['offset'] = $offset;
        $data['count'] = $count;
        $data['status_list'] = '';
        $data = json_encode($data);
        $res = $this->creat_curl($url,$data);
        $res = json_decode($res,true);
        return $res;
    }

    /**
     * 获取用户卡券列表
     */
    public function get_card_list($open_id)
    {
        $url = 'https://api.weixin.qq.com/card/user/getcardlist?access_token='.$this->access_token;
        $data['openid'] = $open_id;
        $data['card_id'] = "";
        $data = json_encode($data);
        $res = $this->creat_curl($url,$data);
        $res = json_decode($res,true);
        return $res;
    }

    /**
     * @param $card_id
     * @return mixed
     * 获取卡券详情
     */
    public function get_card_info($card_id)
    {
        $url = 'https://api.weixin.qq.com/card/get?access_token='.$this->access_token;
        $data['card_id'] = $card_id;
        $data = json_encode($data);
        $res = $this->creat_curl($url,$data);
        $res = json_decode($res,true);
        return $res;
    }

    /**
     * @param $card_id
     * @param $code
     * @return mixed
     * 查看卡券code状态是否可用
     */
    public  function get_card_status($card_id,$code)
    {
        $url = 'https://api.weixin.qq.com/card/code/get?access_token='.$this->access_token;
        $data['card_id'] = $card_id;
        $data['code'] = $code;
        $data['check_consume'] = true;
        $data = json_encode($data);
        $res = $this->creat_curl($url,$data);
        $res = json_decode($res,true);
        return $res;
    }

    /**
     * @param $code
     * 核销微信卡券
     */
    public function consume_card($code)
    {
        $url = 'https://api.weixin.qq.com/card/code/consume?access_token='.$this->access_token;
        $data['code'] = $code;
        $data = json_encode($data);
        $res = $this->creat_curl($url,$data);
        $res = json_decode($res,true);
        return $res;
    }

    /**
     * @param $openid
     * @return mixed
     * 获取用户的详情以及是否关注
     */
    public function get_user_info($openid)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$this->access_token.'&openid='.$openid.'&lang=zh_CN';

        $res = $this->creat_curl($url);
        $res = json_decode($res,true);
        return $res;
    }

    public function get_openid($code)
    {
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->secret.'&code='.$code.'&grant_type=authorization_code';
        $res = $this->creat_curl($get_token_url);
        $res = json_decode($res,true);
        return $res;
    }

    public function get_login_user_info($token)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$this->appid.'&lang=zh_CN';
        $res = wx_common::creat_curl($url);
        $res = json_decode($res,true);
        return $res;
    }

    public function get_login_url()
    {
        $return_url = request()->url(true);
        $return_url = urlencode($return_url);
        $state = $this->getRandChar(20);//生成20位随机数
        return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$return_url.'&response_type=code&scope=snsapi_userinfo&state='.$state.'#wechat_redirect';

    }
}